package org.chen.aao.subscription.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.api.services.androidpublisher.model.SubscriptionPurchase;
import org.chen.aao.common.exception.BusinessException;
import org.chen.aao.common.subscription.dto.SubscriptionStatusResponse;
import org.chen.aao.common.subscription.dto.ValidateRequest;
import org.chen.aao.common.subscription.dto.ValidationResponse;
import org.chen.aao.common.subscription.entity.Subscription;
import org.chen.aao.subscription.mapper.SubscriptionMapper;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.model.ProductPurchase;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class SubscriptionService {
    
    private final AndroidPublisher androidPublisher;
    private final SubscriptionMapper subscriptionMapper;
    private final RedisTemplate<String, Object> redisTemplate;
    
    @Value("${google.play.package-name}")
    private String packageName;

    @Transactional
    public ValidationResponse validatePurchase(ValidateRequest request, Long userId) {
        try {
            // 检查是否是订阅产品
            boolean isSubscription = request.getProductId().contains("monthly") ||
                    request.getProductId().contains("yearly");

            if (isSubscription) {
                return validateSubscriptionPurchase(request, userId);
            } else {
                return validateOneTimePurchase(request, userId);
            }
        } catch (Exception e) {
            log.error("Purchase validation error for user {}: {}", userId, e.getMessage());
            return ValidationResponse.builder()
                    .valid(false)
                    .message("验证失败：" + e.getMessage())
                    .build();
        }
    }

    private ValidationResponse validateSubscriptionPurchase(ValidateRequest request, Long userId) throws Exception {
        // 调用Google Play API验证订阅
        SubscriptionPurchase purchase = androidPublisher.purchases()
                .subscriptions()
                .get(packageName, request.getProductId(), request.getPurchaseToken())
                .execute();

        // 检查订阅状态
        if (purchase.getPaymentState() == null || purchase.getPaymentState() != 1) {
            return ValidationResponse.builder()
                    .valid(false)
                    .message("订阅支付状态无效")
                    .build();
        }

        // 检查是否已处理过这个订单
        String orderId = purchase.getOrderId();
        Subscription existing = subscriptionMapper.selectOne(
                new QueryWrapper<Subscription>()
                        .eq("order_id", orderId)
                        .eq("user_id", userId)
        );

        if (existing != null && "ACTIVE".equals(existing.getStatus())) {
            return ValidationResponse.builder()
                    .valid(true)
                    .subscription(existing)
                    .message("订阅已存在")
                    .build();
        }

        // 创建或更新订阅记录
        Subscription subscription = existing != null ? existing : new Subscription();
        subscription.setUserId(userId);
        subscription.setProductId(request.getProductId());
        subscription.setOrderId(orderId);
        subscription.setPurchaseToken(request.getPurchaseToken());
        subscription.setPurchaseTime(LocalDateTime.ofInstant(
                Instant.ofEpochMilli(purchase.getStartTimeMillis()),
                ZoneId.systemDefault()
        ));
        subscription.setExpiryTime(LocalDateTime.ofInstant(
                Instant.ofEpochMilli(purchase.getExpiryTimeMillis()),
                ZoneId.systemDefault()
        ));
        subscription.setStatus("ACTIVE");
        subscription.setPlan(determinePlan(request.getProductId()));
        subscription.setAutoRenew(purchase.getAutoRenewing());
        subscription.setPrice(determinePrice(request.getProductId()));
        subscription.setCurrency("CNY");

        if (existing != null) {
            subscriptionMapper.updateById(subscription);
        } else {
            subscriptionMapper.insert(subscription);
        }

        // 更新缓存
        updateSubscriptionCache(userId, subscription);

        // 发送订阅成功通知
        sendSubscriptionNotification(userId, subscription);

        return ValidationResponse.builder()
                .valid(true)
                .subscription(subscription)
                .message("订阅验证成功")
                .build();
    }

    private ValidationResponse validateOneTimePurchase(ValidateRequest request, Long userId) throws Exception {
        // 验证一次性购买
        ProductPurchase purchase = androidPublisher.purchases()
                .products()
                .get(packageName, request.getProductId(), request.getPurchaseToken())
                .execute();

        if (purchase.getPurchaseState() != 0) {
            return ValidationResponse.builder()
                    .valid(false)
                    .message("购买状态无效")
                    .build();
        }

        // 处理一次性购买逻辑
        // ...

        return ValidationResponse.builder()
                .valid(true)
                .message("购买验证成功")
                .build();
    }

    public SubscriptionStatusResponse getSubscriptionStatus(Long userId) {
        // 先从缓存获取
        String cacheKey = "subscription:status:" + userId;
        SubscriptionStatusResponse cached = (SubscriptionStatusResponse) redisTemplate.opsForValue().get(cacheKey);

        if (cached != null) {
            return cached;
        }

        // 查询数据库
        Subscription subscription = subscriptionMapper.selectOne(
                new QueryWrapper<Subscription>()
                        .eq("user_id", userId)
                        .eq("status", "ACTIVE")
                        .orderByDesc("expiry_time")
                        .last("LIMIT 1")
        );

        SubscriptionStatusResponse response;
        if (subscription != null) {
            response = SubscriptionStatusResponse.builder()
                    .hasActiveSubscription(true)
                    .plan(subscription.getPlan())
                    .expiryTime(subscription.getExpiryTime())
                    .autoRenew(subscription.getAutoRenew())
                    .build();
        } else {
            response = SubscriptionStatusResponse.builder()
                    .hasActiveSubscription(false)
                    .plan("FREE")
                    .build();
        }

        // 缓存结果
        redisTemplate.opsForValue().set(cacheKey, response, 10, TimeUnit.MINUTES);

        return response;
    }

    @Transactional
    public void cancelSubscription(Long userId) {
        Subscription subscription = subscriptionMapper.selectOne(
                new QueryWrapper<Subscription>()
                        .eq("user_id", userId)
                        .eq("status", "ACTIVE")
                        .orderByDesc("expiry_time")
                        .last("LIMIT 1")
        );

        if (subscription == null) {
            throw new BusinessException("没有找到有效的订阅");
        }

        try {
            // 调用Google Play API取消订阅
            androidPublisher.purchases()
                    .subscriptions()
                    .cancel(packageName, subscription.getProductId(), subscription.getPurchaseToken())
                    .execute();

            // 更新数据库
            subscription.setStatus("CANCELLED");
            subscription.setAutoRenew(false);
            subscriptionMapper.updateById(subscription);

            // 清除缓存
            clearSubscriptionCache(userId);

            log.info("Subscription cancelled for user {}", userId);
        } catch (Exception e) {
            log.error("Failed to cancel subscription for user {}: {}", userId, e.getMessage());
            throw new BusinessException("取消订阅失败");
        }
    }

    // 定时任务：检查订阅过期
    @Scheduled(cron = "0 0 * * * ?") // 每小时执行一次
    public void checkExpiredSubscriptions() {
        log.info("Starting subscription expiry check...");

        LocalDateTime now = LocalDateTime.now();
        List<Subscription> expiredSubscriptions = subscriptionMapper.selectList(
                new QueryWrapper<Subscription>()
                        .eq("status", "ACTIVE")
                        .lt("expiry_time", now)
        );

        for (Subscription subscription : expiredSubscriptions) {
            try {
                // 再次验证Google Play状态
                SubscriptionPurchase purchase = androidPublisher.purchases()
                        .subscriptions()
                        .get(packageName, subscription.getProductId(), subscription.getPurchaseToken())
                        .execute();

                if (purchase.getExpiryTimeMillis() < System.currentTimeMillis()) {
                    // 确认已过期
                    subscription.setStatus("EXPIRED");
                    subscriptionMapper.updateById(subscription);

                    // 清除缓存
                    clearSubscriptionCache(subscription.getUserId());

                    // 发送过期通知
                    sendExpiryNotification(subscription.getUserId());
                } else {
                    // 更新过期时间
                    subscription.setExpiryTime(LocalDateTime.ofInstant(
                            Instant.ofEpochMilli(purchase.getExpiryTimeMillis()),
                            ZoneId.systemDefault()
                    ));
                    subscriptionMapper.updateById(subscription);
                }
            } catch (Exception e) {
                log.error("Error checking subscription {}: {}", subscription.getId(), e.getMessage());
            }
        }

        log.info("Subscription expiry check completed. Processed {} subscriptions", expiredSubscriptions.size());
    }

    // 定时任务：同步订阅状态
    @Scheduled(cron = "0 30 * * * ?") // 每小时30分执行
    public void syncSubscriptionStatus() {
        log.info("Starting subscription status sync...");

        List<Subscription> activeSubscriptions = subscriptionMapper.selectList(
                new QueryWrapper<Subscription>()
                        .eq("status", "ACTIVE")
                        .eq("auto_renew", true)
        );

        for (Subscription subscription : activeSubscriptions) {
            try {
                SubscriptionPurchase purchase = androidPublisher.purchases()
                        .subscriptions()
                        .get(packageName, subscription.getProductId(), subscription.getPurchaseToken())
                        .execute();

                // 更新订阅信息
                subscription.setExpiryTime(LocalDateTime.ofInstant(
                        Instant.ofEpochMilli(purchase.getExpiryTimeMillis()),
                        ZoneId.systemDefault()
                ));
                subscription.setAutoRenew(purchase.getAutoRenewing());

                if (purchase.getCancelReason() != null) {
                    subscription.setStatus("CANCELLED");
                }

                subscriptionMapper.updateById(subscription);

                // 更新缓存
                updateSubscriptionCache(subscription.getUserId(), subscription);

            } catch (Exception e) {
                log.error("Error syncing subscription {}: {}", subscription.getId(), e.getMessage());
            }
        }

        log.info("Subscription status sync completed. Processed {} subscriptions", activeSubscriptions.size());
    }

    private void updateSubscriptionCache(Long userId, Subscription subscription) {
        String cacheKey = "user:subscription:" + userId;
        redisTemplate.opsForValue().set(cacheKey, subscription.getPlan(), 1, TimeUnit.HOURS);

        String detailKey = "subscription:detail:" + userId;
        redisTemplate.opsForHash().put(detailKey, "plan", subscription.getPlan());
        redisTemplate.opsForHash().put(detailKey, "expiryTime", subscription.getExpiryTime().toString());
        redisTemplate.opsForHash().put(detailKey, "status", subscription.getStatus());
        redisTemplate.opsForHash().put(detailKey, "autoRenew", subscription.getAutoRenew().toString());
        redisTemplate.expire(detailKey, 1, TimeUnit.HOURS);

        // 清除状态缓存
        String statusKey = "subscription:status:" + userId;
        redisTemplate.delete(statusKey);
    }

    private void clearSubscriptionCache(Long userId) {
        redisTemplate.delete("user:subscription:" + userId);
        redisTemplate.delete("subscription:detail:" + userId);
        redisTemplate.delete("subscription:status:" + userId);
    }

    private String determinePlan(String productId) {
        if (productId.contains("premium")) {
            return "PREMIUM";
        } else if (productId.contains("basic")) {
            return "BASIC";
        }
        return "FREE";
    }

    private BigDecimal determinePrice(String productId) {
        // 根据产品ID返回价格
        if (productId.contains("premium_yearly")) {
            return new BigDecimal("499.00");
        } else if (productId.contains("premium_monthly")) {
            return new BigDecimal("59.90");
        } else if (productId.contains("basic_monthly")) {
            return new BigDecimal("19.90");
        }
        return BigDecimal.ZERO;
    }

    private void sendSubscriptionNotification(Long userId, Subscription subscription) {
        // 发送订阅成功通知（可以通过邮件、推送等方式）
        log.info("Sending subscription notification to user {}: plan={}", userId, subscription.getPlan());
        // TODO: 实现通知逻辑
    }

    private void sendExpiryNotification(Long userId) {
        // 发送订阅过期通知
        log.info("Sending expiry notification to user {}", userId);
        // TODO: 实现通知逻辑
    }

}